package com.bangdream.michelia.view.activity.currency;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bangdream.michelia.BuildConfig;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.UserContract;
import com.bangdream.michelia.entity.UserMsgBean;
import com.bangdream.michelia.presenter.UserPresenter;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.PublicResources;
import com.bangdream.michelia.utils.PublicUtil;
import com.bangdream.michelia.utils.SPUtils;
import com.bangdream.michelia.view.activity.exam.ExamInfoActivity;
import com.jaeger.library.StatusBarUtil;
import com.bangdream.michelia.R;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.utils.MyLog;
import com.bangdream.michelia.view.activity.base.BaseActivity;
import com.mob.tools.utils.UIHandler;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by Mr.Wang on 2018/3/29.
 * 909732184@qq.com
 * 用户登录
 */

public class LoginActivity extends BaseActivity<UserContract.IUserView,UserPresenter<UserContract.IUserView>>
        implements View.OnClickListener ,UserContract.IUserView,PlatformActionListener{
    private static final String TAG = "UserSignIn";
    private EditText editPhoneNumber,editPassWord,editVerificationCode;
    private TextView btnGetCode,btnGo;
    private LinearLayout codeLayout,btnQqSignIn,btnWeChatSignIn;
    //连续登录错误3次需要输入验证码
    private int errorIndex;
    private ThirdUserType thirdUserType;
    //第三方登录授权回调的方法好像是在子线程 使用Handler将结果传出来更新Ui
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pd.dismiss();
            switch (msg.what){
                case 1:
                    authorize(ShareSDK.getPlatform(QQ.NAME));
                    break;
                    default:break;
            }
        }
    };

    //第三方用户类型 qq用户登录 微信用户登录
    enum ThirdUserType{
        QQ{public String getValue(){ return "5"; }},
        WEICHAT{public String getValue(){ return "4"; }};
        public abstract String getValue();
    }

    @Override
    public int getLayout() {
        return R.layout.activity_sign_in;
    }

    @Override
    public void findId() {
        if(AppCurrentUser.getInstance().isSign()){
            startActivity(new Intent(this,MainActivity.class));
            finish();
        }
        editPhoneNumber = findViewById(R.id.editPhoneNumber);
        editPassWord = findViewById(R.id.editPassWord);
        editVerificationCode = findViewById(R.id.editVerificationCode);
        btnGo = findViewById(R.id.btnGo);
        btnGetCode = findViewById(R.id.btnGetCode);
        codeLayout = findViewById(R.id.codeLayout);
        btnQqSignIn = findViewById(R.id.btnQqSignIn);
        btnWeChatSignIn = findViewById(R.id.btnWeChatSignIn);

    }

    @Override
    public void logic() {
        /**
         * 设置全屏并且显示状态栏
         */
        //5.0以上系统才支持这个效果 app内容占据导航栏 并且导航栏透明
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }else {
            StatusBarUtil.setColorNoTranslucent(this, ContextCompat.getColor(this, R.color.white));
        }
        if(BuildConfig.DEBUG){
//            editPhoneNumber.setText("13733182759");
//            editPassWord.setText("123456");
        }
    }

    @Override
    public UserPresenter createPresenter() {
        UserPresenter presenter = new UserPresenter();
        presenter.setPd(pd);
        return presenter;
    }

    @Override
    public void setListener() {
        btnGetCode.setOnClickListener(this);
        btnGo.setOnClickListener(this);
        btnQqSignIn.setOnClickListener(this);
        btnWeChatSignIn.setOnClickListener(this);
        editPhoneNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“next 下一项”键*/
                if(actionId == EditorInfo.IME_ACTION_NEXT){
                    //点击下一项 密码输入框获取焦点
                    editPassWord.requestFocus();
                    editPassWord.setSelection(editPassWord.getText().toString().length());
                    return true;
                }
                return false;
            }
        });
//        //将输入法切换到英文
//        editPassWord.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        editPassWord.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“GO”键*/
                if(actionId == EditorInfo.IME_ACTION_GO){
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    onClick(btnGo);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.btnGo:
                //startActivity(new Intent(this, ExamInfoActivity.class));
                actionLogin();
                break;
            case R.id.btnGetCode:
                if(PublicUtil.isMobileNO(editPhoneNumber.getText().toString())){
                    //获取验证码
                    getVerificationCode();
                }else {
                    showText("请输入正确的手机号");
                }
                break;
            case R.id.btnForgetPassword:
                intent = new Intent(this,RetrievePasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.btnRegister:
                intent = new Intent(this,RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.btnCodeSignIn:
                //getVerificationCode();
                intent = new Intent(this,CodeLoginActivity.class);
                startActivity(intent);
                finish();
                break;
             //第三方登录 - qq
            case R.id.btnQqSignIn:
                //Platform plat = ShareSDK.getPlatform(QQ.NAME);
                //plat.showUser(null);
                thirdUserType = ThirdUserType.QQ;
                authorize(ShareSDK.getPlatform(QQ.NAME));
                break;
            //第三方登录 - 微信
            case R.id.btnWeChatSignIn:
                thirdUserType = ThirdUserType.WEICHAT;
                authorize(ShareSDK.getPlatform(Wechat.NAME));
                break;
                default:
                    break;
        }
    }
    //登录
    private void actionLogin() {
        String stUserName = editPhoneNumber.getText().toString();
        String stPassword = editPassWord.getText().toString();
        String stCode = editVerificationCode.getText().toString();
        if(checkStrEmpty(stUserName,"请输入用户名")
                ||checkStrEmpty(stPassword,"请输入密码")
                ||(codeLayout.getVisibility()==View.VISIBLE&&checkStrEmpty(stCode,"请输入验证码"))){
            return;
        }
        //取消用户登录之后的信息保存
        SPUtils.put(LoginActivity.this,"userName",stUserName);
        SPUtils.put(LoginActivity.this,"pwd",stPassword);
        mPresenter.actionLogin(stUserName,stPassword,stCode);
    }

    //获取验证码
    private void getVerificationCode(){
        mPresenter.getVerificationCode(UserContract.CodeType.LOGINPHONE,editPhoneNumber.getText().toString(),pd);
    }

    /**
     * 开始计时 两次获取验证码间隔60秒
     */
    private void stateTime(){
        final long count = 60;
        Observable.interval(0, 1, TimeUnit.SECONDS)         //延时几秒，每隔几秒开始执行
                //超过多少秒停止执行
                .take(count + 1)
                //类型转换，由于是倒计时，案例需要将倒计时的数字反过来
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) {
                        //MyLog.d("apply",aLong+"=aLong\n"+(count - aLong));
                        return count - aLong;
                    }
                })
                //观察者在主线程执行
                .observeOn(AndroidSchedulers.mainThread())
                //设置订阅观察者
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        MyLog.d(TAG,"执行过程中");
                    }
                })
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        MyLog.d(TAG,"开始执行");
                        seetingButtonState(false);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        MyLog.d(TAG,"剩余" + aLong + "秒");
                        btnGetCode.setText( aLong +"s");
                    }

                    @Override
                    public void onError(Throwable e){
                        seetingButtonState(true);
                    }

                    @Override
                    public void onComplete(){
                        MyLog.d(TAG,"执行完毕");
                        seetingButtonState(true);
                    }
                });
    }

    @Override
    public void setRegisterCode(boolean isSuccess, String stDescribe) {
        if(isSuccess){
            btnGetCode.setText(stDescribe);
            //获取验证码请求成功之后调用开始计时60秒后才能再次获取
            //stateTime();
        }else {
            showText(stDescribe+"");
        }
    }

    @Override
    public void actionRegister(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void actionLogin(boolean isSuccess, String stDescribe) {
        if(isSuccess){
            Intent intent = new Intent(this,MainActivity.class);
            startActivity(intent);
            finish();
        }else {
            showText(stDescribe);
            errorIndex++;
        }
        if(errorIndex>=1){
            codeLayout.setVisibility(View.VISIBLE);
            //获取验证码
            onClick(btnGetCode);
        }
    }

    @Override
    public void actionFindPassword(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void setUserMsg(boolean isSuccess, UserMsgBean userMsgBean) {

    }

    /**
     * 设置按钮状态 获取验证码按钮可以点击与不可点击时的两种效果
     */
    private void seetingButtonState(boolean ifOn){
        btnGetCode.setEnabled(ifOn);
        if(ifOn){
            btnGetCode.setText("获取验证码");
            btnGetCode.setBackgroundColor(ContextCompat.getColor(LoginActivity.this,R.color.common_red));
            btnGetCode.setTextColor(ContextCompat.getColor(LoginActivity.this,R.color.white));
        }else {
            btnGetCode.setBackgroundColor(ContextCompat.getColor(LoginActivity.this,R.color.VerificationCodeOff));
            btnGetCode.setTextColor(ContextCompat.getColor(LoginActivity.this,R.color.black_text));
        }
    }

    //申请第三方授权登录
    private void authorize(final Platform plat) {
        if (plat == null) {
            return;
        }
        //判断指定平台是否已经完成授权
        if(plat.isAuthValid()) {
            String userId = plat.getDb().getUserId();
            if (userId != null) {
                //UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
                actionThirdLogin(plat,thirdUserType);
                return;
            }
        }
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(true);
        //获取用户资料
        plat.showUser(null);
        pd.show();
    }
    //第三方用户登录
    private void actionThirdLogin(Platform plat,ThirdUserType type){
        if (plat==null||type==null)
            return;
        String userId = plat.getDb().getUserId();
        String nickName = plat.getDb().getUserName();
        String userIcon = plat.getDb().getUserIcon();
        mPresenter.actionThirdLogin(userIcon,nickName,userId,type.getValue());
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        sendMessage(1);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        L.e(throwable.getMessage()+"");
        sendMessage(2);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        showText("取消授权");
        sendMessage(2);
    }

    private void sendMessage(int type){
        Message message = new Message();
        message.what=type;
        mHandler.sendMessage(message);
    }
}
